<?php
namespace Usap\Service\CMS;

use Usap\Service\Service;
use Think\Cache;
class news{
	
	
	
	/**
	 * 删除某个栏目的缓存
	 * @param unknown $category_id
	 */
	public function clearContentCacheByCategory($category_id, $part_id = ''){
		
		if(empty($category_id)) return ;
        $key = !empty($part_id) ? "category:{$part_id}:".$category_id.'*' : 'category:'.$category_id.'*';

        $cache_obj = Cache::singleton('redis');
		$key_list = $cache_obj->keys('category:'.$category_id.'*');
		if($key_list){

			foreach ($key_list  as $key) {
				
				$cache_obj->del($key);
			}
		}
		
	}
	

	
	/**
	 * 设置某个栏目的文章缓存
	 * @param int $category_id
	 * @param string $key
	 * @param * $content
	 */
	public function setContentCacheByCategory($category_id,$cache_key,$cache_content, $part_id = ''){
		
		if(empty($category_id) || empty($cache_key) || empty($cache_content)) return ;
		
		$cache_obj = Cache::singleton('redis');

        $key = !empty($part_id) ? "category:{$part_id}:".$category_id.':'.md5($cache_key) : 'category:'.$category_id.':'.md5($cache_key);

//        $key = 'category:'.$category_id.':'.md5($cache_key);
		$cache_obj->set($key,$cache_content,60*60);//缓存1小时
	}
	
	
	
	/**
	 * 获取缓存文章内容
	 * @param unknown $category_id
	 * @param unknown $cache_key
	 */
	public function getContentCacheByCategory($category_id,$cache_key, $part_id = ''){

		if(empty($category_id) || empty($cache_key)) return ;
		
		$cache_obj = Cache::singleton('redis');

        $key = !empty($part_id) ?  "category:{$part_id}:".$category_id.':'.md5($cache_key) : 'category:'.$category_id.':'.md5($cache_key);

//        $key = 'category:'.$category_id.':'.md5($cache_key);
		return $cache_obj->get($key);
	}
	
	
	
	/**
	 * 根据文章ID获取详情内容
	 * @param unknown $uuid
	 */
	public function getDetailCacheByUUID($uuid){
		
		if(empty($uuid)) return array();
		
		$cache_obj = Cache::singleton('redis');
		
		$key = 'essay:'.$uuid;
		return $cache_obj->get($key);
	}
	
	
	
	/**
	 * 根据文章ID清理内容缓存
	 * @param unknown $uuid
	 */
	public function clearDetailCacheByUUID($uuid){
		
		if(empty($uuid)) return ;
		
		$cache_obj = Cache::singleton('redis');
		$cache_key = 'essay:'.$uuid;
		return $cache_obj->del($cache_key);
	}
	
	
	
	/**
	 * 设置文章内容
	 * @param unknown $uuid
	 * @param unknown $content
	 */
	public function setDetailCacheByUUID($uuid,$content){
		
		if(empty($uuid) || empty($content)) return ; 

		$cache_obj = Cache::singleton('redis');
		
		$cache_key = 'essay:'.$uuid;
		$cache_obj->set($cache_key,$content,60*60);//缓存1小时
	}
	
	
	
	public function getCategoryConfByID($catid, $part_id = ''){
		
		
		$func_args = func_get_args();
		$cache_key = 'getcategoryconbyid_'.var_export($func_args,true);
		
		$cache_content_list = $this->getContentCacheByCategory($catid,$cache_key, $part_id);
		if($cache_content_list){
			
			return $cache_content_list;
		}

		$where_str = "disabled='0' AND ismenu='1' AND catid='$catid' ";
		$list =  D("Usap/Admin/Category")->where($where_str)->order("listorder asc")->find();
		if(empty($list)){

			return array();
		}
		
		$this->setContentCacheByCategory($catid, $cache_key, $list);
		return $list;
	}
	
	
	/**
	 * 获取指定栏目配置
	 * @param array $category_items
	 * @return multitype:|multitype:unknown
	 */
	public function getCategoryConf($category_items=array(), $part_id = ''){
		
		
		$where_str = "disabled='0' AND ismenu='1' " .(empty($part_id) ? '' :" AND part_id='$part_id' ");
		
		if(!empty($category_items)){
			$category_str = "'".implode("','", $category_items)."'";
			$where_str .= " AND catname in ($category_str) ";
		}
		
		$list =  D("Usap/Admin/Category")->where($where_str)->order("listorder asc")->select();
		if(empty($list)){
			
			return array();
		}
		$result_list = array();
		foreach ($list as $key=>$value){
			
			$result_list[$value['catid']] = $value;
		}
		
		//$this->setContentCacheByCategory($catid, $cache_key, $list);
		return $result_list;
	}
	
	
	/*
	 * 根据 栏目主键ID 获取对应  文章数据
	 */
	/**
	 *  
	 * @param unknown $category_id
	 * @param number $page
	 * @param number $page_size
	 * @return multitype:number multitype: |multitype:number unknown
	 */
	public function getListByCategoryId($category_id, $page=1, $page_size=20, $part_id = '', $location_id = ''){

		$result=array('total'=>0,'list'=>array());
		if(empty($category_id) || !is_numeric($category_id))	return $result;
		
		
		/*———从缓存中获取数据———*/
		$func_args = func_get_args();
		$cache_key = 'getlistbycategoryid_'.var_export($func_args,true);
		$cache_content_list = $this->getContentCacheByCategory($category_id,$cache_key, $part_id);

		if($cache_content_list){

			return $cache_content_list;
		}
		
		$where_str = "catid='$category_id' " .(empty($part_id) ? '' : " AND part_id='$part_id' ");
		
		//先根据栏目定位表
		$category_info=D('Usap/Admin/Category')->field("model,catname")->where($where_str)->find();
		if(empty($category_info))	return $result;
		$model = ucfirst($category_info['model']);

        !$location_id ?: $where_str .= ' AND city_id = ' .$location_id;
		
		
		//查询符合栏目对应的文章记录数
		$count=D("Usap/Admin/$model")->where($where_str)->count();
		if(empty($count))	return $result; 
		
		$page_size = ($page_size<0) ? 20 : $page_size;
		$start = ($page-1) <=0 ? 0 : (intval($page)-1)*$page_size;
		
		
		if($model == 'Article'){
			$article_list = D("Usap/Admin/$model")->where($where_str . " AND `status`='agree'" )->order("istop desc,updatetime desc")->limit($start, $page_size)->select();
			$result_info=$article_list;
		}

		if($model == 'Page'){
			$page_list = D("Usap/Admin/$model")->where($where_str ." AND `status`='agree'")->order("updatetime desc")->limit($start,$page_size)->select();
			$result_info=$page_list;
		}

        \Logger::getLogger('wifi.service.news')->apps('getListByCategoryId')->info(array('mrk'=>'获取新闻', 'host' => SITE_URL, 'part_info' => $part_info, 'sql'=>D("Usap/Admin/$model")->_sql()));

        if(empty($result_info))		return $result;
		
		foreach($result_info as $k=>&$v){
			
			//获取栏目名称
			$v['catname'] = $category_info['catname'];

			//重构图片地址
			if($v['thumb']){
				$thumb_url_info = parse_url($v['thumb']);
				$v['thumb'] = $thumb_url_info['path'];
			}else{
				$v['thumb'] = '';
			}

			if($v['carousel']){
				$carousel_url_info = parse_url($v['carousel']);
				$v['carousel'] = $carousel_url_info['path'];
			}else{
				$v['carousel'] = '';
			}
			
		}

		$result=array(
			'total'=>$count,'page'=>$page,'page_size'=>$page_size,'list'=>$result_info
		);

		/*———设置缓存数据———*/
		$this->setContentCacheByCategory($category_id,$cache_key,$result, $part_id);
		return $result;
	}
	/*
	 * 83d46b07-f62a-11e5-96af-f8bc1236d2a0
	 1-8fe9198af61611e596aff8bc1236d2a0 (8-4-4-4-12)
	array(
		'code'=>0000(!0000，错误信息见msg)
		'msg'=>'',
		'data'=>array   数据列表
);
	 */
	public function getDetailInfoByUID($uuid){

		$result =array();
		if(empty($uuid)) return $result;
		
		$uuid_info = explode('-',$uuid);

		$category_id = $uuid_info[0];//栏目ID
		$article_id = $uuid_info[1];//文章ID
		
		$cache_list = $this->getDetailCacheByUUID($uuid);
		if(!empty($cache_list)){
			
			return $cache_list;
		}
		
		//根据栏目ID获取表
		$category_info=D('Usap/Admin/Category')->field("model,catname")->where("catid=$category_id")->find();
		if(empty($category_info))	return array('code'=>'CATEGORY_ERROR','msg'=>'没有指定栏目的文章');
		$model = ucfirst($category_info['model']);
		
		$model_list = D("Usap/Admin/$model")->where("uuid='$article_id'")->find();
		if(empty($model_list))		return array('code'=>'CATEGORY_ERROR','msg'=>'没有指定栏目的文章');

		$model_list['catname'] = $category_info['catname'];

		$info =  array(
			'code'=>'0000','msg'=>'成功','data'=>$model_list
		);
		
		$this->setDetailCacheByUUID($uuid,$info);
		return $info;
	}
	
	
	/**
	 * 审核文章
	 * @param string $uuid
	 * @param string $audit_result
	 */
	public function auditNessay($uuid, $audit_result,$auditor='system', $part_id){

		if(empty($uuid) || empty($audit_result)) return array('code'=>'PARAM_ERROR','msg'=>'参数不合法');

		$uuid_info = explode('-',$uuid);

		$category_id = $uuid_info[0];//栏目ID
		$article_id = $uuid_info[1];//文章ID

		//删除文章缓存
		$this->clearDetailCacheByUUID($uuid);


		//删除栏目缓存
		$this->clearContentCacheByCategory($category_id, $part_id);
		

		$article_detail = $this->getDetailInfoByUID($uuid);
		if($article_detail['data']['status']!='not'){

			$this->ajaxReturn(array('code'=>'ERROR','msg'=>'该文章已经审核，不能继续处理'));
		}
		
		

		$category_info=D('Usap/Admin/Category')->field("model,catname")->where("catid=$category_id")->find();
		if(empty($category_info))	return array('code'=>'CATEGORY_ERROR','msg'=>'没有指定栏目的文章');
		$model = ucfirst($category_info['model']);
		
		$opt_result =  D("Usap/Admin/$model")->where("uuid='$article_id'")->save(array('status'=>$audit_result,'audittime'=>time(),'auditor'=>$auditor));
		if(!$opt_result){

			return array('code'=>'OPT_ERROR','msg'=>'系统处理异常');
		}
		$this->clearDetailCacheByUUID($uuid);
		return array('code'=>'0000','msg'=>'处理成功');
	}
	

	
	/**
	 * 获取单个地址的PV统计信息
	 * @param unknown $url
	 */
	public function getPVTallyNo($url){

		if(empty($url)) return 0;		

		$cache_obj = Cache::singleton('redis');
		$url_info = parse_url($url);
		$tally_url = trim($url_info['host'].$url_info['path'],'/');//统计的目标url
		$cache_key = 'CMSTally:stat:'.$tally_url;
		
		$hit_no = $cache_obj->hget($cache_key,'PV');
		return empty($hit_no) ? 0 : $hit_no;
	}
	
	
	/**
	 * 统计PV(Page View)
	 * @param unknown $url
	 */
	public function PVTally($url){

		$cache_obj = Cache::singleton('redis');
		$url_info = parse_url($url);

		//分析过滤文章uri(统计到域名且参数忽略)
		$match_url = trim(parse_url($url,PHP_URL_PATH),"\/");

		$category_id = $article_id = '';
		if(preg_match('/article\/([1-9]+[-][a-z0-9]*)$/i', $match_url,$match_list)){//匹配文章

			$article_info  = explode('-',$match_list[1]);
			$category_id = $article_info[0];
			$article_id = $article_info[1];
		}elseif(preg_match('/article\/listing\/([1-9]*)$/i', $match_url,$match_list)){//匹配栏目

			$category_id = $match_list[1];
		}

		$tally_url = trim($url_info['host'].$url_info['path'],'/');//统计的目标url
// dprint($tally_url);
		$stat_hash_key = "CMSTally:stat:".$tally_url;
		$day_hash_key = "CMSTally:".date('Y-m-d').":".$tally_url;
		
		
		//按天统计
		$field_val = $cache_obj->hget($day_hash_key,'PV');
		if(empty($field_val)){

			$cache_obj->hset($day_hash_key,'PV',1);
		}else{
			$cache_obj->hincrby($day_hash_key,'PV',1);
		}

		//汇总统计
		$field_val = $cache_obj->hget($stat_hash_key,'PV');
		if(empty($field_val)) {
			
			$cache_obj->hset($stat_hash_key,'PV',1);
		}else{
			$cache_obj->hincrby($stat_hash_key,'PV',1);
		}

	}
	
	public function getUrl(){
		
	
		$url = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
		$url .= $_SERVER['HTTP_HOST'];
		$url .= isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : urlencode($_SERVER['PHP_SELF']) . '?' . urlencode($_SERVER['QUERY_STRING']);
		return $url;
	
	}


	/**
	 * 获取头条新闻
	 *
	 * @param int $page
	 * @param int $page_size
	 * @param string $part_id
	 * @param string $location_id
	 * @param bool $is_cache
	 */
	public function getHeadList($page=1, $page_size=20, $part_id = '', $location_id = '', $is_cache = false)
	{
		$res_info = array();
		$cache_key = 'top_head_' .md5(json_encode(func_get_args()));
		if($is_cache){
			$res_info = $this->getContentCacheByCategory(-1, $cache_key);

			if(!empty($res_info)){ return $res_info; }
		}

		$condition = array();
		$condition['ishead'] = array('EQ', 1);
		$condition['status'] = array('EQ', 'agree');
//		$condition['part_id'] = array('EQ', $part_id);

		$list_count = D("Usap/Admin/Article")
			->where($condition)
			->count();

		$page - 1 >= 0 ?: $page = 1;

		if($list_count){


			$list_res = D("Usap/Admin/Article")
				->where($condition)
				->order("updatetime desc")
				->limit(($page - 1) * $page_size, $page_size)->select();
	
			//  数据结构 和 getList 获取的 结构保持一致
			foreach($list_res as $k=>&$v){
				$v['catname'] = '点石彩头条';
				//重构图片地址
				$v['thumb'] =  $v['thumb'] ? parse_url($v['thumb'])['path'] : '';
			}

			$res_info = array(
				'total' => $list_count,
				'list' => $list_res
			);
			$this->setContentCacheByCategory(-1, $cache_key, $res_info, $part_id);
		}
		return $res_info;
	}
	
}
